package com.bc.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.jraf.android.backport.switchwidget.Switch;

import com.bc.R;
import com.bc.db.DBHelper;
import com.bc.db.dao.WarnDao;
import com.bc.db.entity.Warn;
import com.bc.utils.Constants;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.view.ActionMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;

public class WarnListActivity extends BaseActivity implements OnItemClickListener, OnItemLongClickListener{
	private ListView mListView;
	
	private WarnListAdapter mAdapter;
	private WarnDao dao;
	private List<Warn> warnList = new ArrayList<Warn>();
	private String btcType;
	
	private ActionMode mActionMode;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_warn_list);
		
		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setTitle(getIntent().getStringExtra(Constants.BTC_NAME_COL) +"-"+getString(R.string.warn_tip));
		
		btcType = getIntent().getStringExtra(Constants.BTC_TYPE_COL);
		mListView = (ListView)findViewById(R.id.list);
		mListView.setEmptyView(findViewById(R.id.empty));
		dao = WarnDao.getInstance(WarnListActivity.this);

		mListView.setOnItemClickListener(this);
		mListView.setOnItemLongClickListener(this);
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		if (mAdapter == null) {
			mAdapter =new WarnListAdapter(WarnListActivity.this);
			mListView.setAdapter(mAdapter);
		}
		warnList.clear();
		warnList = dao.queryItems(Constants.BTC_TYPE_COL +"=?", new String[]{ btcType });
		Log.d(getClass().getSimpleName(), "warnList#size: " + warnList.size());
		mAdapter.notifyDataSetChanged();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_warn_list, menu);
		return true;
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add_warn:
			Intent intent = new Intent(WarnListActivity.this, WarnAddActivity.class);
			intent.putExtra(Constants.BTC_TYPE_COL, getIntent().getStringExtra(Constants.BTC_TYPE_COL));
			startActivity(intent);
			overridePendingTransition(R.anim.push_in_right, R.anim.push_out_left);
			break;
		case android.R.id.home:
			finish();
			overridePendingTransition(R.anim.push_in_left, R.anim.push_out_right);
			break;
		default:
			break;
		}
		return true;
	}
	
	public class WarnListAdapter extends BaseAdapter {
		
		public WarnListAdapter(Context context) {

		}
		@Override
		public int getCount() {
			return warnList.size();
		}

		@Override
		public Object getItem(int position) {
			return warnList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(WarnListActivity.this).inflate(R.layout.adapter_warn_list, parent, false);
			}
			final Warn warn = (Warn) getItem(position);
			if (mSelectedHashMap.containsKey(warn.id)) {
				Log.d("WarnListActivity", "contain id: " + warn.id);
				convertView.setBackgroundColor(getResources().getColor(R.color.list_item_selected));
			} else {
				convertView.setBackgroundColor(getResources().getColor(R.color.white));
				Log.d("WarnListActivit", "not contain id: " + warn.id);
			}
			TextView warnTextView = (TextView)convertView.findViewById(R.id.warn_text);
			String tipText = getResources().getStringArray(R.array.warn_price_array)[warn.buy];
			tipText += getResources().getStringArray(R.array.warn_type_array)[warn.over];
			tipText += getString(R.string.formate_money, warn.money+"");
			warnTextView.setText(tipText);
			
			Switch settingSwitch = (Switch)convertView.findViewById(R.id.setting_switch);
			settingSwitch.setChecked(warn.enable == 1);
			settingSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					warn.enable = isChecked ? 1 : 0;
					dao.updateItem(warn, DBHelper.ID_COL + "=?", new String[]{warn.id +""});
				}
			});
			return convertView;
		}
		
	}
	
	private HashMap<Integer, Boolean> mSelectedHashMap = new HashMap<Integer, Boolean>();
	class ActionBarCallBack implements ActionMode.Callback {

		@Override
		public boolean onActionItemClicked(ActionMode arg0, MenuItem menuItem) {
			switch (menuItem.getItemId()) {
			case R.id.action_delete:
				
				WarnDao dao = WarnDao.getInstance(WarnListActivity.this);
				Iterator<Integer> iterator = mSelectedHashMap.keySet().iterator();
				String[] ids = new String[mSelectedHashMap.size()];
				int index = 0;
				while (iterator.hasNext()) {
					ids[index ++] = iterator.next().toString();
				}
				dao.deleteItems(ids);
				mSelectedHashMap.clear();
				warnList.clear();
				warnList = dao.queryItems(Constants.BTC_TYPE_COL +"=?", new String[]{ btcType });
				Log.d(getClass().getSimpleName(), "warnList#size: " + warnList.size());
				mAdapter.notifyDataSetChanged();
				mActionMode.finish();
				mActionMode = null;
				break;

			default:
				break;
			}
			return true;
		}

		@Override
		public boolean onCreateActionMode(ActionMode arg0, Menu menu) {
			getMenuInflater().inflate(R.menu.activity_warn_list_select, menu);
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode arg0) {
			mSelectedHashMap.clear();
			mActionMode = null;
			mAdapter.notifyDataSetChanged();
		}

		@Override
		public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
			return false;
		}
		
	}
	


	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		
		if (mActionMode == null) {
			mActionMode = startSupportActionMode(new ActionBarCallBack());
		}
		checkSelectItem(position);
		return true;
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		if (mActionMode != null) {
			checkSelectItem(position);
		}
		
	}
	
	public void checkSelectItem(int position) {
		Warn warn = warnList.get(position);
		Object object = mSelectedHashMap.get(Integer.valueOf(warn.id));
		if (object == null) {
			mSelectedHashMap.put(warn.id, true);
		} else {
			mSelectedHashMap.remove(warn.id);
		}
		updateSelectState();
		mAdapter.notifyDataSetChanged();
	}
	
	public void updateSelectState() {
		if (mSelectedHashMap.size() > 0) {
			if (mActionMode != null) {
				mActionMode.setTitle(getString(R.string.selected, mSelectedHashMap.size()));
			}
		} else {
			if (mActionMode != null) {
				mActionMode.finish();
				mActionMode = null;
			}
		}
	}
}
